//
// 队列使用示例
// Created by kenny on 25-11-8.
//

#include "mcp_queue.h"
#include "mcp_logger.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>


// 1. 定义你的数据结构
typedef struct {
    uint8_t protocol;
    uint8_t version;
    uint16_t sequence;
    uint8_t* data;          // 动态分配
    uint16_t data_length;
} SimplePacket;

// 2. 定义拷贝函数（由队列在入队时调用）
void* custom_packet_copy(void* dest, const void* src, size_t element_size) {
    printf("element_size: %p\n", &element_size);
    const SimplePacket* src_packet = (const SimplePacket*)src;
    SimplePacket* dest_packet = (SimplePacket*)dest;

    // 复制基本字段
    *dest_packet = *src_packet;  // 直接结构体赋值

    // 深度拷贝data字段
    if (src_packet->data && src_packet->data_length > 0) {
        dest_packet->data = malloc(src_packet->data_length);
        memcpy(dest_packet->data, src_packet->data, src_packet->data_length);
    } else {
        dest_packet->data = NULL;
        dest_packet->data_length = 0;
    }

    return dest;
}

// 3. 定义释放函数（由队列在清空或销毁时调用）
void custom_packet_free(void* element) {
    SimplePacket* packet = (SimplePacket*)element;
    if (packet->data) {
        free(packet->data);
        packet->data = NULL;
    }
    packet->data_length = 0;
}

// 4. 业务层使用（非常简单）
int main_back() {
    // 创建队列时注册管理函数
    mcp_queue_t* queue = mcp_queue_create(100,
        sizeof(SimplePacket),custom_packet_copy,custom_packet_free);

    // 入队示例
    SimplePacket packet = {0};
    packet.protocol = 1;
    packet.version = 1;
    packet.sequence = 100;
    packet.data_length = strlen("Hello") + 1;
    packet.data = (uint8_t*)malloc(packet.data_length);
    strcpy((char*)packet.data, "Hello");

    // 入队：队列会自动深度拷贝，业务层可以立即释放原数据
    mcp_queue_enqueue(queue, &packet);
    free(packet.data);  // 立即释放原数据，队列中有独立副本
    packet.data = NULL;

    // 出队示例
    SimplePacket received;
    if (mcp_queue_dequeue(queue, &received) == 0) {
        // 使用received中的数据...
        LOG_INFO("Data: %s\n", received.data);

        // 业务层不需要手动释放，下次入队或队列销毁时会自动清理
    }

    // 销毁队列：自动调用custom_packet_free释放所有元素
    mcp_queue_destroy(queue);

    return 0;
}